import { defineStore } from "pinia";
import { store } from "../index";
import { constantRouterMap, asyncRouterMap } from "@/router/index";
// 深拷贝函数
import { cloneDeep } from "lodash-es";

export interface PermissionState {
  // 整体路由信息
  routers: AppRouteRecordRaw[];
  // 添加的路由
  addRouters: AppRouteRecordRaw[];
  // 是否添加了路由
  isAddRouters: boolean;
}

export const usePermissionStore = defineStore("permission", {
  state: (): PermissionState => {
    return {
      routers: [],
      addRouters: [],
      isAddRouters: false,
    };
  },
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      return this.routers;
    },
    getAddRouters(): AppRouteRecordRaw[] {
      return cloneDeep(this.addRouters);
    },
    getIsAddRouters(): boolean {
      return this.isAddRouters;
    },
  },
  actions: {
    generateRoutes(permissions?: string[]) {
      let accessedRoutes: AppRouteRecordRaw[] = [];
      if (permissions && permissions.length >= 0) {
        accessedRoutes = this.filterRoutes(
          cloneDeep(asyncRouterMap),
          permissions
        );
      }
      // 添加404路由
      this.addRouters = accessedRoutes.concat([
        {
          path: "/:path(.*)*",
          redirect: "/404",
          name: "404Page",
          meta: {
            hidden: true,
            breadcrumb: false,
          },
        },
      ]);
      let newRouters = cloneDeep(constantRouterMap).concat(this.addRouters);
      const homeRoute = newRouters.find((item) => item.path == "/");
      if (homeRoute) {
        homeRoute.redirect = accessedRoutes[0]?.path || "/";
      }
      this.routers = newRouters;
    },
    setIsAddRouters(state: boolean): void {
      this.isAddRouters = state;
    },
    filterRoutes(routesMap: AppRouteRecordRaw[], permissions: string[]) {
      const res: AppRouteRecordRaw[] = [];
      routesMap.forEach((route) => {
        const tmp = { ...route };
        if (this.hasPermission(permissions, tmp)) {
          if (tmp.children) {
            tmp.children = this.filterRoutes(tmp.children, permissions);
          }
          res.push(tmp);
        }
      });
      return res;
    },
    hasPermission(permissions: string[], route: AppRouteRecordRaw) {
      if (route.meta && route.meta.permission) {
        // some 是数组的「存在性校验方法」遍历数组的每个元素，对每个元素执行「回调函数」；只要有 至少一个元素 让回调函数返回 true
        return permissions.some((permission) =>
          route.meta.permission.includes(permission)
        );
      } else {
        return true;
      }
    },
  },
});

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store);
};
